import { useState } from 'react';
import type { TablePaginationConfig } from 'antd';
interface Sorter {
  field?: string;
  order?: 'ascend' | 'descend';
}

const usePagination = (initialParams?: { pageSize?: number }) => {
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: initialParams?.pageSize || 10,
    total: 0,
    orderBy: undefined as string | undefined,
    orderType: undefined as 'asc' | 'desc' | undefined
  });

  const handleTableChange = (
    newPagination: TablePaginationConfig,
    filters: unknown,
    sorter: Sorter | Sorter[]
  ) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current || 1,
      pageSize: newPagination.pageSize || 10,
      orderBy: sorter?.field,
      orderType: sorter?.order?.replace('end', '') // 转换antd的排序参数
    }));
  };

  const resetPagination = () => {
    setPagination(prev => ({
      ...prev,
      current: 1
    }));
  };

  return {
    paginationParams: {
      current: pagination.current,
      pageSize: pagination.pageSize,
      orderBy: pagination.orderBy,
      orderType: pagination.orderType
    },
    handleTableChange,
    setPagination,
    resetPagination,
    paginationConfig: {
      current: pagination.current,
      pageSize: pagination.pageSize,
      total: pagination.total,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条`,
      showQuickJumper: true
    } as TablePaginationConfig
  };
};

export default usePagination;
